package org.truenewx.tnxjee.repo.mybatis.mapper;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.truenewx.tnxjee.repo.mybatis.MyBatisRelationMapperRepository;
import org.truenewx.tnxjee.repo.mybatis.MyBatisUnityMapperRepository;

@Component
public class EntityMapperPostProcessor implements BeanPostProcessor, ApplicationContextAware {

    private BeanDefinitionRegistry beanDefinitionRegistry;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.beanDefinitionRegistry = (BeanDefinitionRegistry) applicationContext.getAutowireCapableBeanFactory();
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        BeanDefinition beanDefinition = null;
        if (bean instanceof UnityMapper) {
            beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(MyBatisUnityMapperRepository.class)
                    .addConstructorArgValue(bean).getBeanDefinition();
        } else if (bean instanceof RelationMapper) {
            beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(MyBatisRelationMapperRepository.class)
                    .addConstructorArgValue(bean).getBeanDefinition();
        }
        if (beanDefinition != null) {
            String repositoryBeanName = beanName + Repository.class.getSimpleName();
            this.beanDefinitionRegistry.registerBeanDefinition(repositoryBeanName, beanDefinition);
        }

        return bean;
    }

}
